package ddd.ajava.chapter4.question1;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class PersonInput implements PersonAction {

	@Override
	public Person process(Person person) {
		List<String> list=this.getLabelValue(person.getClass());//获取每个@Label上的中文名称
		int count=list.size();
		List<String> list2=this.getInput(count,list);//输入的参数数据
		
		try {
			person=(Person) this.setAttr(person.getClass(), list2);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		/*for(int i=0;i<count;i++){
			System.out.print(list.get(i)+list2.get(i)+" ");
			
		}*/
		return person;
	}
	//设置参数
	protected Object setAttr(Class<?> clazz,List<String> list){
		Field fields[]=clazz.getDeclaredFields();
		Method methods[]=clazz.getMethods();
		Object person=null;
		try{
			person=clazz.newInstance();
			for(int i=0;i<fields.length;i++){
				if(fields[i].getType().getName()=="java.lang.String"){
					String setter="set"+StringUtil.firstCharToUp(fields[i].getName());
					for(Method method:methods){
						String methodName=method.getName();
						if(methodName.equals(setter)){
							method.invoke(person, list.get(i));
							break;
						}
					}
				}else if(fields[i].getType().getName()=="int"){
					String setter="set"+StringUtil.firstCharToUp(fields[i].getName());
					for(Method method:methods){
						String methodName=method.getName();
						if(methodName.equals(setter)){
							method.invoke(person, (Integer.valueOf(list.get(i)).intValue()));
//							System.out.println(methodName);
							break;
						}
					}
				}else if(fields[i].getType().getName()=="java.lang.Boolean"){
					String setter="set"+StringUtil.firstCharToUp(fields[i].getName());
					for(Method method:methods){
						String methodName=method.getName();
						if(methodName.equals(setter)){
							method.invoke(person,Boolean.valueOf(list.get(i)).booleanValue());
//							System.out.println(methodName);
							break;
						}
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return person;
	}
//  获取每个标注上的中文名称
	private List<String> getLabelValue(Class<?> clazz) {
		List<String> list = new ArrayList<String>();
		Field fields[]= clazz.getDeclaredFields();
		for(Field field:fields){
//			Class cl=field.getType();
			Label lb=field.getAnnotation(Label.class);
			list.add("请输入" + lb.name()+":");
		}
		return list;
	}
	
	//获取从键盘输入的数据
	private List<String> getInput(int count,List<String> list){
		List<String> list2=new ArrayList<String>();
		Scanner sc=new Scanner(System.in);
		int i=0;
		while(i<count){
			System.out.println(list.get(i));
			if(sc.hasNext()){
				list2.add(sc.next());
			}else{
				break;
			}
//			System.out.println(list2.get(i));
			i++;
		}
		return list2;
	}
}
